import json
from typing import Any, Union

def encode(message: Union[str, dict, list, int, float, bool]) -> bytes:
    """
    将消息编码为 bytes，如果是非字符串对象，先转换为 JSON 字符串
    """
    if not isinstance(message, str):
        message = json.dumps(message, ensure_ascii=False)
    return (message + "\n").encode('utf-8')


def decode(data: bytes, parse_json: bool = True) -> Any:
    """
    将 bytes 解码为字符串，如果 parse_json=True 且内容是 JSON，则自动反序列化
    """
    text = data.decode('utf-8').strip()
    if parse_json:
        try:
            return json.loads(text)
        except json.JSONDecodeError:
            return text
    return text